#include "interface.h"


Database::Database(std::string dbfile)
{
    if(sqlite3_open(dbfile.c_str(), &db))
    {
        std::cout << sqlite3_errmsg(db) << std::endl;
        sqlite3_close(db);
        db = nullptr;
        return;
    }

    char *errmsg;
    std::string sqlcmd;
    sqlcmd = "create table if not exists punch(id text, time integer)";
    if(sqlite3_exec(db, sqlcmd.c_str(), nullptr, nullptr, &errmsg) != SQLITE_OK)
    {
        std::cout << errmsg << std::endl;
        sqlite3_free(errmsg);
    }
    sqlcmd = "create table if not exists employee(id text primary key, name text)";
    if(sqlite3_exec(db, sqlcmd.c_str(), nullptr, nullptr, &errmsg) != SQLITE_OK)
    {
        std::cout << errmsg << std::endl;
        sqlite3_free(errmsg);
    }
}

Database::~Database()
{
    if(!db) return;
    sqlite3_close(db);
    db = nullptr;
}

int Database::punch(std::string id, time_t time)
{
    if(!db)
    {
        std::cout << "database open fail!" << std::endl;
        return 1;
    }

    char *errmsg;
    std::string sqlcmd = "insert into punch values(\"" + id + "\"," + std::to_string(time) +");";
    if(sqlite3_exec(db, sqlcmd.c_str(), nullptr, nullptr, &errmsg) != SQLITE_OK)
    {
        std::cout << errmsg << std::endl;
        sqlite3_free(errmsg);
        return 2;
    }
    return 0;
}

int Database::getname(std::string id, std::string& name)
{
    char **result;
    int rows;
    int cols;
    char *errmsg;
    std::string sqlcmd = "select name from employee where id = \"" + id + "\";";
    if(sqlite3_get_table(db, sqlcmd.c_str(), &result, &rows, &cols, &errmsg) != SQLITE_OK)
    {
        std::cout << errmsg << std::endl;
        sqlite3_free(errmsg);
        return 2;
    }
    (rows == 0) ? (name = "user not exist!") : (name = result[(rows+1)*cols - 1]);
    return 0;
}
